using MediatR;
using S.O.Api.Read.Application.Command.Medical;
using S.O.Domain.Medical;
using S.O.ErrorCode;
using S.O.Interstructrue.Base;

namespace S.O.Api.Read.Application.Handler.Medical
{
    /// <summary>
    /// 获取医生列表处理器
    /// 用于挂号时的医生选择
    /// </summary>
    public class GetDoctorListHandler : IRequestHandler<GetDoctorListCommand, APIResult<List<DoctorDto>>>
    {
        /// <summary>
        /// 医生仓储
        /// </summary>
        private readonly IBaseRepository<DoctorModel> _doctorRepository;

        /// <summary>
        /// 构造函数，通过依赖注入初始化所需服务
        /// </summary>
        /// <param name="doctorRepository">医生仓储</param>
        public GetDoctorListHandler(IBaseRepository<DoctorModel> doctorRepository)
        {
            _doctorRepository = doctorRepository;
        }

        /// <summary>
        /// 处理获取医生列表命令
        /// </summary>
        /// <param name="request">查询命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>医生列表</returns>
        public async Task<APIResult<List<DoctorDto>>> Handle(GetDoctorListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 构建查询条件
                var query = _doctorRepository.GetALL().Where(d => !d.IsDeleted);
                
                // 如果指定了科室，按科室筛选
                if (!string.IsNullOrEmpty(request.Department))
                {
                    query = query.Where(d => d.Department == request.Department);
                }
                
                // 如果只返回在职医生
                if (request.OnlyActive)
                {
                    query = query.Where(d => d.WorkStatus == "在职" && d.IsEnable);
                }
                
                // 按医生姓名排序
                query = query.OrderBy(d => d.DoctorName);
                
                // 执行查询
                var doctors = query.ToList();
                
                // 转换为DTO
                var dtoList = doctors.Select(d => new DoctorDto
                {
                    Id = d.Id,
                    DoctorCode = d.DoctorCode,
                    DoctorName = d.DoctorName,
                    Title = d.Title,
                    Department = d.Department,
                    Specialty = d.Specialty,
                    Introduction = d.Introduction,
                    RegistrationFee = d.RegistrationFee,
                    WorkStatus = d.WorkStatus
                }).ToList();
                
                return new APIResult<List<DoctorDto>> { Code = APIEnums.Success, Data = dtoList, Msg = "获取医生列表成功" };
            }
            catch (Exception ex)
            {
                return new APIResult<List<DoctorDto>> { Code = APIEnums.Error, Msg = $"获取医生列表失败：{ex.Message}" };
            }
        }
    }
}